import { gsap } from 'gsap';
import { SplitText } from 'gsap/SplitText';
gsap.registerPlugin(SplitText);


export class Charming{
    constructor(opts) {
        const setting = {
            charsName:'[data-chars]',
            wordName:'[data-word]',
            lineName:'[data-lines]',
            textName:"[data-text]"
        }
        this.opt =  Object.assign(setting,opts);
        this.colNum=1;
        this.charsElm = document.querySelectorAll(this.opt.charsName);
        this.wordElm = document.querySelectorAll(this.opt.wordName);
        this.textElm = document.querySelectorAll(this.opt.textName);
        this.lineElm = document.querySelectorAll(this.opt.lineName);
        let split_chars = SplitText.create(this.charsElm, { type: "chars",charsClass:"letter" });
        let split_word = SplitText.create(this.wordElm, { type: "words",wordsClass:"letter" });
        const that = this;
        setTimeout(function(){
            let split_line = SplitText.create(that.lineElm, { type: "lines",linesClass:"letter" });
        },2000);
        this.textElm.forEach(item=>{
            this.charming(item, 'letter',item.dataset.split||"");
        });
    }
    charming(elem,cls,split_){
        var self = this,
            array = elem.getAttribute('data-text').split(split_);
        elem.innerHTML = '';
        var colNum = 0;
        var Fragment = document.createDocumentFragment();
        array.forEach(function (item,i) {
            var span = document.createElement("span");
            var str = 'wordLine'+colNum;
            if(item==='|'){
                span=document.createElement("br");
                colNum++;
            }else {
                span.classList.add(cls);
                span.classList.add(str);
                span.innerText = item;
            }
            Fragment.appendChild(span);
        });
        elem.appendChild(Fragment);
    }
}